package de.ipk_gatersleben.bit.bi.edal.publication.attribute.panel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.CellEditor;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.MatteBorder;
import javax.swing.table.DefaultTableModel;

import de.ipk_gatersleben.bit.bi.edal.publication.AttributeLabel;
import de.ipk_gatersleben.bit.bi.edal.publication.AttributeTablePanel;
import de.ipk_gatersleben.bit.bi.edal.publication.Utils;
import de.ipk_gatersleben.bit.bi.edal.publication.PropertyLoader;
import de.ipk_gatersleben.bit.bi.edal.publication.PublicationFrame;
import de.ipk_gatersleben.bit.bi.edal.publication.PublicationMainPanel;
import de.ipk_gatersleben.bit.bi.edal.publication.PublicationModul;

public class SubjectPanel extends JPanel implements ActionListener {

	private static final long serialVersionUID = 8109825692298261311L;

	private static final AttributeLabel SUBJECTS_LABEL = new AttributeLabel(
			PropertyLoader.props.getProperty("SUBJECTS_LABEL"),
			PropertyLoader.props.getProperty("SUBJECTS_TOOLTIP"));;

	private static final JButton OKAY_BUTTON = new JButton("OK");
	private static final JButton ADD_BUTTON = new JButton("ADD SUBJECT");
	private static final JButton REMOVE_BUTTON = new JButton("REMOVE SUBJECT");

	private DefaultTableModel model;
	private JTable table;

	private static final String[] DEFAULT_VALUE = new String[] { "" };

	public SubjectPanel() {

		GridBagLayout grid = new GridBagLayout();

		JPanel mainPanel = new JPanel(grid);

		mainPanel.setBackground(PropertyLoader.MAIN_BACKGROUND_COLOR);

		model = new MyTableModel();
		table = new JTable(model);

		table.setFillsViewportHeight(true);
		table.setFont(PropertyLoader.DEFAULT_FONT);
		table.setForeground(PropertyLoader.MAIN_FONT_COLOR);
		table.getTableHeader().setFont(PropertyLoader.DEFAULT_FONT);
		table.getTableHeader().setForeground(PropertyLoader.MAIN_FONT_COLOR);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getTableHeader().setBorder(
				BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK));

		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		buttonPanel.setBackground(PropertyLoader.MAIN_BACKGROUND_COLOR);

		buttonPanel.add(OKAY_BUTTON);
		buttonPanel.add(ADD_BUTTON);
		buttonPanel.add(REMOVE_BUTTON);

		OKAY_BUTTON.addActionListener(this);
		ADD_BUTTON.addActionListener(this);
		REMOVE_BUTTON.addActionListener(this);

		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setPreferredSize(new Dimension(400, 100));

		Utils.addComponent(mainPanel, grid, scrollPane, 0, 0, 1, 1, 1, 1, 1, 1);
		Utils.addComponent(mainPanel, grid, buttonPanel, 0, 1, 1, 1, 1, 1, 1, 1);

		JPanel attributePanel = new JPanel(new BorderLayout());

		SubjectPanel.SUBJECTS_LABEL.setForeground(PropertyLoader.LABEL_COLOR);

		attributePanel.add(SubjectPanel.SUBJECTS_LABEL, BorderLayout.NORTH);
		attributePanel.setBackground(PropertyLoader.MAIN_BACKGROUND_COLOR);
		attributePanel.setPreferredSize(new Dimension(40,
				PropertyLoader.DEFAULT_FONT_SIZE));

		this.setBorder(new MatteBorder(0, 0, 1, 0, Color.BLACK));

		GridBagLayout gridbaglayout = new GridBagLayout();

		this.setLayout(gridbaglayout);
		this.setBackground(PropertyLoader.MAIN_BACKGROUND_COLOR);

		Utils.addComponent(this, gridbaglayout, attributePanel, 0, 0, 1, 1,
				0.02, 1, 50, 10);
		Utils.addComponent(this, gridbaglayout, mainPanel, 1, 0, 1, 1, 0.98, 1,
				50, 10);

	}

	@Override
	public void actionPerformed(ActionEvent actionEvent) {

		if (actionEvent.getSource().equals(OKAY_BUTTON)) {

			CellEditor cellEditor = table.getCellEditor();
			if (cellEditor != null) {
				if (cellEditor.getCellEditorValue() == null) {
					cellEditor.stopCellEditing();
				}
			}

			/* clear(unselect) selected rows */
			this.table.clearSelection();

			/* remove rows without any name */
			ArrayList<Integer> emptyLines = new ArrayList<Integer>();

			for (int i = 0; i < this.table.getRowCount(); i++) {
				if (Utils.checkIfStringIsEmpty(this.model.getValueAt(i, 0)
						.toString())) {
					emptyLines.add(i);
				}
			}

			for (int i = emptyLines.size() - 1; i >= 0; i--) {
				this.model.removeRow(emptyLines.get(i));
			}

			PublicationMainPanel.subjectPanel = this;

			PublicationMainPanel.subjectsField.setText(getTableContent());

			PublicationMainPanel.releaseAllBlockedFields();

			PublicationMainPanel.getMainPanel().remove(
					PublicationMainPanel.SUBJECTS_PANEL_COMPONENT_NUMBER);

			PropertyLoader.SUBJECTS_LABEL
					.setForeground(PropertyLoader.LABEL_COLOR);

			PublicationMainPanel.getMainPanel().add(
					new AttributeTablePanel(PropertyLoader.SUBJECTS_LABEL,
							PublicationMainPanel.subjectsField,
							PropertyLoader.THREE_TIMES_SIZE),
					PublicationMainPanel.SUBJECTS_PANEL_COMPONENT_NUMBER);

			PublicationFrame.updateUI();
			PublicationModul.getFrame().requestFocusInWindow();

		} else if (actionEvent.getSource().equals(ADD_BUTTON)) {

			if (this.table.getSelectedRow() != -1) {
				this.model.insertRow(this.table.getSelectedRow() + 1,
						DEFAULT_VALUE);
			} else {
				this.model.addRow(DEFAULT_VALUE);
			}

		}

		else if (actionEvent.getSource().equals(REMOVE_BUTTON)) {

			if (this.model.getRowCount() != 0) {
				if (this.table.getSelectedRow() != -1) {

					this.model.removeRow(this.table.getSelectedRow());
				} else {
					this.model.removeRow(this.model.getRowCount() - 1);
				}
			}
		}

	}

	private class MyTableModel extends DefaultTableModel {

		private static final long serialVersionUID = 8557354261856948625L;

		private String[] colNames = { "Subject" };
		private Object[][] data = { { "Bioinformatics" } };

		public MyTableModel() {
			setDataVector(data, colNames);
		}
	}

	private String getTableContent() {

		String nameSeperator = new String(", ");

		StringBuffer buffer = new StringBuffer("");

		for (int i = 0; i < this.model.getRowCount(); i++) {
			if (!Utils.checkIfStringIsEmpty(this.model.getValueAt(i, 0)
					.toString())) {
				buffer.append(this.model.getValueAt(i, 0).toString());
				buffer.append(nameSeperator);
			}

		}

		if (buffer.toString().lastIndexOf(nameSeperator) != -1) {
			return buffer.toString().substring(0,
					buffer.toString().lastIndexOf(nameSeperator));
		} else {
			return PublicationMainPanel.DEFAULT_SUBJECTS_STRING;
		}
	}

	public String[] getSubjects() {

		String[] subjects = new String[this.model.getRowCount()];

		for (int i = 0; i < this.model.getRowCount(); i++) {

			subjects[i] = this.model.getValueAt(i, 0).toString();
		}
		return subjects;
	}

}
